package serverCommunicator;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import common.CommandAnswer;
/**
 * ServerCommunicator - handle the communication between the client
 * 						this class open in separate thread-
 * 						read the Command from client, execute the command 
 * 						by server implementation of the interface, and return the answer to server
 * @author Orit
 *
 */


class ServerCommunicator implements Runnable {
	
	private Socket socket;	//open communication with this socket
    
    /**
     * C'tor open separate thread.
     * @param socket
     */
    public ServerCommunicator(Socket socket) {
        this.socket = socket;
        Thread t = new Thread(this);
        t.start();
    }
    
    /**
     * read the Command from client, execute the command by server implementation 
     * 		of the interface, and return the Command answer to server
     */
    public void run() {
    	ObjectInputStream ois = null;
    	common.CommandExecutor command = null;
        try{
            // Read a message sent by client application
            ois = new ObjectInputStream(socket.getInputStream());
            command = (common.CommandExecutor) ois.readObject();
            ServerInterfaceImp.getInstance().init();
            command.setServerInterface(ServerInterfaceImp.getInstance());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } 
        //execute the command by server implementation
	   CommandAnswer answer;
		try {
			answer = command.execute();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			answer = new CommandAnswer();
			answer.setErrorMessege(e.getMessage());
		}
		
	   try{
		// Send a response information to the client application
		   ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
		   oos.writeObject(answer);

		   ServerInterfaceImp.getInstance().close();
	       oos.close();
	       ois.close();
	       socket.close();
	   }catch (IOException e) {
           e.printStackTrace();
       } 

    }
}
